package com.ruoyi.school.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.FileTypeEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.school.convert.PacActualOutputParticipationConverter;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.vo.ActualOutputParticipationListVo;
import com.ruoyi.school.enums.AuditTypeEnum;
import com.ruoyi.school.service.*;
import com.ruoyi.school.mapper.PacActualOutputParticipationMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author jeremylin
* @description 针对表【pac_actual_output_participation(学术成果参与表)】的数据库操作Service实现
* @createDate 2025-07-10 03:15:20
*/
@Service
public class PacActualOutputParticipationServiceImpl extends ServiceImpl<PacActualOutputParticipationMapper, PacActualOutputParticipation>
    implements PacActualOutputParticipationService{

    @Resource
    private StudentService studentService;

    @Resource
    private PacTeacherService pacTeacherService;

    @Resource
    private PacAuditRecordsService pacAuditRecordsService;

    @Resource
    private PacActualOutputService pacActualOutputService;

    /**
     * 参与学术成果
     *
     * @param pacAcademicOutput
     * @return
     */
    @Override
    public boolean join(PacActualOutputParticipation pacAcademicOutput) {
        validateJoin(pacAcademicOutput);
        // 插入学生信息
        Long stuId = pacAcademicOutput.getParticipantId();
        Student student = studentService.getById(stuId);
        pacAcademicOutput.setParticipantName(student.getStuName());
        pacAcademicOutput.setParticipantNum(student.getStuNum());
        pacAcademicOutput.setParticipantArea(student.getSmallTeam());

        PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if(pacTeacher != null){
            pacAcademicOutput.setAcademicTeacherId(pacTeacher.getId().longValue());
        }

        if(Objects.nonNull(pacAcademicOutput.getAcFile())){
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacAcademicOutput.getAcFile());
            pacAcademicOutput.setAcFileType(fileTypeName.getCode());
        }

        if (save(pacAcademicOutput)) {
//            PacAuditRecords pacAuditRecords = getPacAuditRecords(pacAcademicOutput, student);
//            if (pacAuditRecordsService.add(pacAuditRecords)) {
//                return true;
//            }
        }
        return false;
    }

    /**
     * 参与人员列表
     *
     * @param pacActualOutputId
     * @return
     */
    @Override
    public List<ActualOutputParticipationListVo> getParticipants(Long pacActualOutputId) {
        List<PacActualOutputParticipation> list = lambdaQuery().eq(PacActualOutputParticipation::getOutputId, pacActualOutputId).list();
        Map<Long, PacActualOutputParticipation> listMap = list.stream().collect(Collectors.toMap(PacActualOutputParticipation::getParticipantId, Function.identity()));

        List<Long> collect = list.stream().map(PacActualOutputParticipation::getParticipantId).collect(Collectors.toList());
        List<Student> sysUsers = studentService.selectByStuIds(collect);
        List<ActualOutputParticipationListVo> vos = PacActualOutputParticipationConverter.INSTANCE.student2Vo(sysUsers);
        vos.forEach(item -> {
            PacActualOutputParticipation pacActualOutputParticipation = listMap.get(item.getId().longValue());
            if(pacActualOutputParticipation != null){
                item.setStatus(pacActualOutputParticipation.getStatus());
                item.setJoinId(pacActualOutputParticipation.getId());
            }
        });
        return vos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        if(id == null){
            throw new RuntimeException("id不能为空");
        }
        removeById(id);
        // 同时删除审批
        // 同时删除审批记录
        pacAuditRecordsService.deleteByOutPutId(id, AuditTypeEnum.PAC_WALL_TYPE_PRACTICE.getCode());
    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @Override
    public PacActualOutputParticipation details(Long id) {
        PacActualOutputParticipation one = lambdaQuery().eq(PacActualOutputParticipation::getId, id).one();
        return one;
    }

    /**
     * 已加入的成员
     *
     * @return
     */
    @Override
    public long countByAudit() {
        return lambdaQuery().eq(PacActualOutputParticipation::getStatus, 2).count();
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteByOutPutId(Long id) {
        lambdaUpdate().eq(PacActualOutputParticipation::getOutputId, id).remove();
    }

    @Override
    public List<Long> selectMemberIds(Long id) {
        List<PacActualOutputParticipation> list = lambdaQuery().eq(PacActualOutputParticipation::getOutputId, id).list();
        if (list != null && list.size() > 0) {
            return list.stream().map(PacActualOutputParticipation::getParticipantId).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * 验证参与
     * @param pacAcademicOutput
     */
    private void validateJoin(PacActualOutputParticipation pacAcademicOutput) {
        if (pacAcademicOutput.getParticipantId() == null) {
            throw new BaseException("请选择参与学生");
        }

        if(pacAcademicOutput.getOutputId() == null){
            throw new BaseException("参与成果不能为空");
        }

        Long participantId = pacAcademicOutput.getParticipantId();

        PacActualOutput pacActualOutput = new PacActualOutput();
        pacActualOutput.setId(pacAcademicOutput.getOutputId());

        PacActualOutput details = pacActualOutputService.getDetails(pacActualOutput);

        if(details.getAcAudit().equals(2)){
            throw new BaseException("该成果已审核通过,无法加入");
        }

        pacActualOutput.setStuId(pacAcademicOutput.getParticipantId());

        if(details.getStuId().equals(participantId)){
            throw new BaseException("无法参与自己的成果");
        }

        PacActualOutputParticipation one = lambdaQuery()
                .eq(PacActualOutputParticipation::getParticipantId, participantId)
                .eq(PacActualOutputParticipation::getOutputId, pacAcademicOutput.getOutputId())
                .one();

        if(Objects.nonNull(one)){
            throw new BaseException("已参与该成果");
        }

        Long count = lambdaQuery().eq(PacActualOutputParticipation::getOutputId, pacAcademicOutput.getOutputId()).count();
        pacAcademicOutput.setJoinIndex((int) (count + 1));
    }

    private PacAuditRecords getPacAuditRecords(PacActualOutputParticipation pacActualOutputParticipation, Student student) {
        // 通过成果id查询详情
        PacActualOutput pacActualOutput = new PacActualOutput();
        pacActualOutput.setId(pacActualOutputParticipation.getOutputId());
        PacActualOutput details = pacActualOutputService.getDetails(pacActualOutput);
        PacAuditRecords pacAuditRecords = new PacAuditRecords();
        pacAuditRecords.setAuditType(AuditTypeEnum.PAC_WALL_TYPE_PRACTICE.getCode());
        pacAuditRecords.setAuditStu(pacActualOutputParticipation.getParticipantName());
        pacAuditRecords.setAuditStuClass(student.getStuClass());
        pacAuditRecords.setAuditTitle(details.getAcTitle());
        pacAuditRecords.setAuditFile(pacActualOutputParticipation.getAcFile());
        pacAuditRecords.setAuditStuId(pacActualOutputParticipation.getParticipantId());
        pacAuditRecords.setAuditRecordId(pacActualOutputParticipation.getId());
        pacAuditRecords.setAuditFileType(pacActualOutputParticipation.getAcFileType());
        return pacAuditRecords;
    }
}




